package com.example.crypt;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


/**
 * RSA加密解密类,负责byte数组的加解密
 *
 * @author wzq
 * @2014年5月4日
 */
/* package */
public class TypeAes implements IByteCrypt {
    private static final String AES_KEY = "AesEncrypt";
    private Cipher encryptCipher = null;// 加密
    private Cipher decryptCipher = null;// 解密

    public TypeAes() {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
            sr.setSeed(AES_KEY.getBytes());
            kgen.init(128, sr); // 192 and 256 bits may not be available
            SecretKey skey = kgen.generateKey();
            byte[] raw = skey.getEncoded();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            //
            encryptCipher = Cipher.getInstance("AES");
            encryptCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            //
            decryptCipher = Cipher.getInstance("AES");
            decryptCipher.init(Cipher.DECRYPT_MODE, skeySpec);
        } catch(NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch(InvalidKeyException e) {
            e.printStackTrace();
        } catch(NoSuchPaddingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 加密byte[]
     *
     * @param bytes
     *
     * @return
     */
    public byte[] encryptBytes(byte[] bytes) {
        try {
            return encryptCipher.doFinal(bytes);
        } catch(IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch(BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密byte[]
     *
     * @param src
     *
     * @return
     */
    public byte[] decryptBytes(byte[] src) {
        try {
            return decryptCipher.doFinal(src);
        } catch(IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch(BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args){
        byte[] bytes = {(byte) 0xaa, (byte) 0xbb};
        TypeAes aes = new TypeAes();
        byte[] encrypted = aes.encryptBytes(bytes);
        System.out.println(CryptUtils.printByteArray(encrypted));
        byte[] decrypted = aes.decryptBytes(encrypted);
        System.out.println(CryptUtils.printByteArray(decrypted));
    }
}
